package com.cqw.commontest.lambda;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-06-01 17:10
 * @Description: 归约（reduce）
 * 归约，也称缩减，是把一个流缩减成一个值，能实现对集合求和，求乘积和求最值的操作
 */
public class StreamTest4 {


    public static void main(String[] args) {

        //1、求和，乘积，最大值
        List<Integer> list = Arrays.asList(1, 3, 5, 6, 7);

        //求和
        Integer sum = list.stream().reduce(Integer::sum).get();
        //10是初始值
        Integer sum1 = list.stream().reduce(10, Integer::sum);

        System.out.println(sum);
        System.out.println(sum1);


        //乘积
        Integer integer = list.stream().reduce((a, b) -> a * b).get();


        //求最大值
        Integer integer1 = list.stream().max(Integer::compareTo).get();

        Integer integer2 = list.stream().reduce(Integer::max).get();

        Integer integer3 = list.stream().reduce((a, b) -> a > b ? a : b).get();


        //求所有员工的工资之和、最高工资
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("张三", 1000, 21, "男", "上海"));
        personList.add(new Person("李四", 2000, 25, "女", "安徽"));
        personList.add(new Person("王五", 2200, 36, "男", "杭州"));
        personList.add(new Person("赵六", 1400, 25, "女", "南京"));
        personList.add(new Person("曹七", 3000, 12, "男", "北京"));
        personList.add(new Person("Lily", 5000, 42, "女", "上海"));

        Integer integer4 = personList.stream().map(Person::getSalary).reduce(Integer::sum).orElse(0);
        System.out.println(integer4);

        Integer integer5 = personList.stream().map(Person::getSalary).max(Comparator.naturalOrder()).orElse(null);
        System.out.println(integer5);


    }

}
